﻿using System;
using System.Collections.Specialized;
using System.Linq;
using Orchard;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Handlers;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.UI.Navigation;
using FruitCake.SimpleGallery.Models;
using FruitCake.SimpleGallery.Services;
using FruitCake.SimpleGallery.ViewModels;
using Orchard.DisplayManagement;
using System.Collections.Generic;

namespace FruitCake.SimpleGallery.Drivers
{

    [OrchardFeature("FruitCake.SimpleGallery")]
    public class SimpleGalleryPartDriver : ContentPartDriver<SimpleGalleryPart>
    {
        private readonly IOrchardServices _Services;
        private readonly ISimpleGalleryService _SimpleGalleryService;

        public SimpleGalleryPartDriver(
            IOrchardServices services,
            ISimpleGalleryService SimpleGalleryService)
        {

            _Services = services;
            _SimpleGalleryService = SimpleGalleryService;

            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        protected override string Prefix { get { return "SimpleGallery"; } }

        protected override DriverResult Display(SimpleGalleryPart part, string displayType, dynamic shapeHelper)
        {
            IEnumerable<SimpleGalleryImage> images = _SimpleGalleryService.GetImages(part).ToArray();
            int imageCount = images.Count();

            // Summary
            if (displayType == "SummaryAdmin")
            {
                return ContentShape(
                    "Parts_SimpleGallery_Admin",
                    () => shapeHelper.Parts_SimpleGallery_Admin(
                        ContentPart: part,
                        Path: part.Path,
                        ImageCount: imageCount,
                        FirstImages: images.Take(5)));
            }

            // Detail
            NameValueCollection queryString = _Services.WorkContext.HttpContext.Request.QueryString;
            int pageIndex = 0;
            if (queryString.AllKeys.Contains("galleryPage"))
            {
                Int32.TryParse(queryString["galleryPage"], out pageIndex);
            }
            if (pageIndex <= 0) pageIndex = 1;

            int pageSize = part.PageSize;

            IEnumerable<SimpleGalleryImage> prevImages = null;
            IEnumerable<SimpleGalleryImage> nextImages = null;

            if (part.LinkMode == LinkMode.LightBox)
            {
                prevImages = images.Take(pageSize * (pageIndex - 1));
            }

            images = images.Skip(pageSize * (pageIndex - 1));

            if (pageSize > 0)
            {
                nextImages = images.Skip(pageSize);
                images = images.Take(pageSize);
            }
            else
            {
                pageSize = imageCount;
            }

            var pager = new ViewModels.SimpleGalleryPagerViewModel(imageCount, pageIndex, pageSize, part.PagerMaxItems);
            
            return Combined(
                ContentShape(
                    "Parts_SimpleGallery_Counter",
                    () => shapeHelper.Parts_SimpleGallery_Counter(pager)),
                ContentShape(
                    "Parts_SimpleGallery",
                    () => shapeHelper.Parts_SimpleGallery(
                        ContentPart: part,
                        PrevImages: prevImages,
                        Images: images,
                        NextImages: nextImages,
                        Path: part.Path)),
                ContentShape(
                    "Parts_SimpleGallery_Pager",
                    () => shapeHelper.Parts_SimpleGallery_Pager(pager))                
                );
        }

        protected override DriverResult Editor(SimpleGalleryPart part, dynamic shapeHelper)
        {
            return Editor(part, null, shapeHelper);
        }

        protected override DriverResult Editor(SimpleGalleryPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            IEnumerable<SimpleGalleryImage> images = _SimpleGalleryService.GetImages(part).ToArray();

            var viewModel = new SimpleGalleryPartEditViewModel
            {
                Path = part.Path,
                PageSize = part.PageSize,
                PagerMaxItems = part.PagerMaxItems,

                FrameWidth = part.FrameWidth,
                FrameHeight = part.FrameHeight,
                EnableThumbnail = part.EnableThumbnail,
                TitleMode = part.TitleMode,
                TitleSeparator = part.TitleSeparator,
                LinkMode = part.LinkMode,

                ImageCount = images.Count(),
                FirstImages = images.Take(5)
            };

            if (updater != null && updater.TryUpdateModel(viewModel, Prefix, null, null))
            {
                // remove any leading slash in the path
                while (!string.IsNullOrEmpty(viewModel.Path) && viewModel.Path[0] == '/')
                {
                    viewModel.Path = viewModel.Path.Substring(1);
                }

                if (viewModel.PageSize < 0) viewModel.PageSize = 0;

                part.Path = viewModel.Path;
                part.PageSize = viewModel.PageSize;
                part.PagerMaxItems = viewModel.PagerMaxItems;

                part.FrameWidth = viewModel.FrameWidth;
                part.FrameHeight = viewModel.FrameHeight;
                part.EnableThumbnail = viewModel.EnableThumbnail;
                part.TitleMode = viewModel.TitleMode;
                part.TitleSeparator = viewModel.TitleSeparator;
                part.LinkMode = viewModel.LinkMode;

                if (!_SimpleGalleryService.IsPathValid(part.Path))
                {
                    if (part.Path[0] == '.' || part.Path.EndsWith("."))
                        updater.AddModelError("Path", T("The \".\" can't be used at either end of the path."));
                    else
                        updater.AddModelError("Path", T("Please do not use any of the following characters in your path: \":\", \"?\", \"#\", \"[\", \"]\", \"@\", \"!\", \"$\", \"&\", \"'\", \"(\", \")\", \"*\", \"+\", \",\", \";\", \"=\", \", \"<\", \">\", \"\\\". No spaces are allowed (please use dashes or underscores instead)."));
                }
            }

            return ContentShape("Parts_SimpleGallery_Edit",
                () => shapeHelper.EditorTemplate(TemplateName: "Parts/SimpleGallery", Model: viewModel, Prefix: Prefix));
        }

        protected override void Importing(SimpleGalleryPart part, ImportContentContext context)
        {
            var path = context.Attribute(part.PartDefinition.Name, "Path");
            if (path != null)
            {
                part.Path = path;
            }
        }

        protected override void Exporting(SimpleGalleryPart part, ExportContentContext context)
        {
            context.Element(part.PartDefinition.Name).SetAttributeValue("Path", String.IsNullOrEmpty(part.Record.Path) ? "/" : part.Record.Path);
        }
    }

}
